package com.gjy.sentinel.core.demo;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;

/**
 * 访问控制
 *
 * @author gjy
 * @version 1.0
 * @since 2025-10-15 15:43:32
 */
public class AuthorityDemo {

    private static final String RESOURCE = "AdminApi";

    /**
     * @param userId 需要校验的用户 ID
     * @return true = 通过白名单，false = 被拦截
     */
    public static boolean tryAccess(int userId) {
        Entry entry = null;
        try {
            entry = SphU.entry(RESOURCE, EntryType.IN, 1, userId);
            System.out.println("[AuthorityDemo] userId=" + userId + " 通过访问控制");
            return true;
        } catch (BlockException be) {
            if (be instanceof AuthorityException) {
                System.out.println("[AuthorityDemo] userId=" + userId + " 被白名单拦截");
            } else {
                System.out.println("[AuthorityDemo] 其它阻塞 => " + be.getClass().getSimpleName());
            }
            return false;
        } finally {
            if (entry != null) entry.exit();
        }
    }

}
